
import { useEffect, useState } from 'react';
import { Table, Tag, Button, Popconfirm, Tooltip, Space, message, Modal, Input } from 'antd';
import { QuestionCircleOutlined } from '@ant-design/icons';
import { userManagement } from '../../../../apis/auth';

const UserManagement = () => {

    const [data, setData] = useState([]);
    const [loading, setLoading] = useState(false);
    const [isModalVisible, setIsModalVisible] = useState(false);
    const [selectedUserId, setSelectedUserId] = useState(null);
    const [newPassword, setNewPassword] = useState('');
    const [current,setCurrent] = useState(1)//设置当前页数
    const [pageSize,setPageSize] = useState(5)//设置每页显示为5条
    const [total, setTotal] = useState(0); // 用户总数

    useEffect(() => {
        fetchData(current,pageSize);
    }, [current,pageSize]);

    const fetchData = async (current , pageSize ) => {
        setLoading(true);
        try {
            const response = await userManagement.getAllUsers(current, pageSize);
            if (response.data.code === 200) {
                setData(response.data.data.list);
                setTotal(response.data.data.total); 
            } else {
                message.error(response.data.message);
            }
        } catch (error) {
            message.error('请求失败，稍后再试');
        } finally {
            setLoading(false);
        }
    };

    const handleChangePassword = async () => {
        if (!newPassword) {
            message.error('请输入新密码');
            return;
        }

        try {
            const response = await userManagement.changePassword({ id: selectedUserId, modifiedPassword: newPassword });
            if (response.data.code === 200) {
                message.success('修改密码成功');
                setIsModalVisible(false);
                setNewPassword('');
                fetchData(current,pageSize); // 重新获取数据
            } else {
                message.error(response.data.message);
            }
        } catch (error) {
            message.error('请求失败，稍后再试');
        }
    };

    const handleDeleteUser = async (id) => {
        try {
            const response = await userManagement.deleteUser(id);
            if (response.data.code === 200) {
                message.success('删除成功');
                fetchData(current,pageSize); // 重新获取数据
            } else {
                message.error(response.data.message);
            }
        } catch (error) {
            message.error('请求失败，稍后再试');
        }
    };

    const showChangePasswordModal = (id) => {
        setSelectedUserId(id);
        setIsModalVisible(true);
    };

    const handleCancel = () => {
        setIsModalVisible(false);
        setNewPassword('');
    };

    const columns = [
        {
            title: '账号',
            dataIndex: 'account',
            key: 'account',
            render: (text) => <a>{text}</a>,
        },
        {
            title: '密码',
            dataIndex: 'password',
            key: 'password',
        },
        {
            title: '姓名',
            dataIndex: 'name',
            key: 'name',
        },
        {
            title: '性别',
            dataIndex: 'sex',
            key: 'sex',
            render: (text) => <Tag color={text === '男' ? 'blue' : 'pink'}>{text}</Tag>,
        },
        {
            title: '电话',
            dataIndex: 'phone',
            key: 'phone',
        },
        {
            title: '地址',
            dataIndex: 'address',
            key: 'address',
        },
        {
            title: '操作',
            key: 'action',
            render: (text, record) => (
                <Space size="middle">
                    <Tooltip title="更改密码">
                        <Button
                            type="link"
                            onClick={() => showChangePasswordModal(record.id)}
                        >
                            更改密码
                        </Button>
                    </Tooltip>
                    <Popconfirm
                        title="你确定要删除这个用户吗？"
                        onConfirm={() => handleDeleteUser(record.id)}
                        icon={<QuestionCircleOutlined style={{ color: 'red' }} />}
                    >
                        <Button type="link">删除用户</Button>
                    </Popconfirm>
                </Space>
            ),
        },
    ];

    return (
        <>
            <Table
                columns={columns}
                dataSource={data}
                loading={loading}
                rowKey="id"
                pagination={{
                    current: current,
                    pageSize: pageSize,
                    total: total,
                    showSizeChanger: true,
                    onChange: (page, pageSize) => {
                    setCurrent(page);
                    setPageSize( pageSize);
                    },
                }}
            />
            <Modal
                title="更改密码"
                open={isModalVisible}
                onOk={handleChangePassword}
                onCancel={handleCancel}
            >
                <Input.Password
                    placeholder="请输入新密码"
                    value={newPassword}
                    onChange={(e) => setNewPassword(e.target.value)}
                />
            </Modal>
        </>
    );
};

export default UserManagement;
